﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ZYB.Security
{
    internal class MD5Tools
    {
        private static readonly string[] HexDigits = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

        public static string ToMD5String(string data)
        {
            if(string.IsNullOrEmpty(data))
                throw new ArgumentNullException(nameof(data));
            var b = Encoding.UTF8.GetBytes(data);
            return ToMD5String(b);

        }

        public static string ToMD5String(byte[] b)
        {
            if(b==null)
                throw new ArgumentNullException(nameof(b));
            var md5 = new MD5CryptoServiceProvider();
            var r = md5.ComputeHash(b, 0, b.Length);
            return ByteArrayToHexString(r);
        }

        private static string ByteArrayToHexString(ICollection<byte> b)
        {
            var sb=new StringBuilder(b.Count);
            foreach (var t in b)
            {
                sb.Append(ByteToHexString(t));
            }
            return sb.ToString();
        }

        private static string ByteToHexString(byte b)
        {
            int n = b;
            var d1 = n / 16;
            var d2 = n % 16;
            return HexDigits[d1] + HexDigits[d2];
        }
    }
}
